from odoo import models, fields, api
from odoo.exceptions import UserError
from datetime import datetime


class BorrowFee(models.Model):
    _name = 'borrow.fee'
    _inherit = ['mail.thread', 'common.state.methods']
    _order = 'id desc'

    name = fields.Char(readonly=True, copy=False)
    request_user = fields.Many2one('res.users', string="申请员工")
    partner_id = fields.Many2one('res.partner', string="合作伙伴")
    return_ids = fields.One2many('return.fee', 'borrow_id', string="还款单据")
    payment_type = fields.Many2one('request.payment.type', string="付款方式")
    amount = fields.Monetary(string='借款额', required=True, currency_field='currency_id' )
    currency_id = fields.Many2one('res.currency', string='Currency', required=True,
                                  default=lambda self: self.env.user.company_id.currency_id)
    payment_date = fields.Datetime('借款日期', default=lambda x: datetime.now())
    discription = fields.Char('备注')
    user_account_name = fields.Char('用户名')
    user_bank_name = fields.Char('开户行')
    user_bank_account = fields.Char('卡号')
    state = fields.Selection([
        ('financial_approve', '员工申请'),
        ('payment_approve', '领导审核'),
        ('boss_approve', '待付款'),
        ('done','待还款'),
        ('clear', '已还清'),
        ('cancelled', '取消')],  default='financial_approve', copy=False, string="状态", track_visibility="onchange")
    return_fee_count = fields.Integer(compute="_compute_return_fee_count", store=True)
    return_fee_total = fields.Monetary('已还款金额', compute="_compute_return_fee_total", store=True)

    @api.multi
    def unlink(self):
        for rec in self:
            if rec.state != 'financial_approve':
                raise UserError('不能删除处于非员工申请状态的借款单据！')
        return super(BorrowFee, self).unlink()

    @api.onchange('request_user')
    def _onchange_bank_account(self):
        for order in self:
            if order.request_user:
                employee = order.request_user.employee_ids
                if employee:
                    employee = employee[0]
                else:
                    raise UserError('没有找到与{}对应的员工！'.format(order.request_user.name))
                order.user_account_name = employee.name
                order.user_bank_name = employee.private_open_bank
                order.user_bank_account = employee.private_bank_account


    @api.depends('return_ids.amount', 'return_ids.state')
    def _compute_return_fee_total(self):
        for order in self:
            return_fee_total = sum(order.return_ids.filtered(lambda x:x.state=='done').mapped('amount'))
            order.return_fee_total = return_fee_total
            #
            #self.change_state(return_fee_total)

    @api.depends('return_ids')
    def _compute_return_fee_count(self):
        for order in self:
            order.return_fee_count = len(order.return_ids)

    @api.multi
    def action_view_return_fee(self):
        form_view_id = self.env.ref('expense.return_fee_form_view').id
        tree_view_id = self.env.ref('expense.return_fee_tree_view').id
        action = {
            'type': 'ir.actions.act_window',
            'views': [(tree_view_id, 'tree'), (form_view_id, 'form')],
            'view_mode': 'tree,form',
            'name': '还款单',
            'res_model': 'return.fee',
            # 'context': dict(self.env.context, is_taxed=self.is_taxed, search_default_group_product=True),
            'domain':[('borrow_id', '=', self.id)]
            }
        return action

    @api.multi
    def return_fee(self):
        action = self.env.ref('sale_extension.sale_order_return_fee_action')
        result = action.read()[0]
        #override the context to get rid of the default filtering
        result['context'] = {'default_borrow_id': self.id,
                            'default_request_user':self.request_user.id,
                            'default_amount':self.amount }

        res = self.env.ref('sale_extension.return_fee_form_view', False)
        result['views'] = [(res and res.id or False, 'form')]
        return result

    def get_bill_name(self):
        name = self.env['ir.sequence'].next_by_code('borrow.fee.name')
        self.name = name

    @api.multi
    def cancel(self):
        self.state = 'cancelled'

    @api.multi
    def financial_approve(self):
        if self.state == 'financial_approve':
            self.state = 'payment_approve'
            if not self.name:
                self.get_bill_name()

    @api.multi
    def payment_approve(self):
        if self.state == 'payment_approve':
            self.state = 'boss_approve'
            # 根据借款单，创建一个付款单明细(expense.line)，方便统一付款
            self._from_borrowfee_to_expensline()

    def _get_borrow_fee_product(self):
        # 获取名为“员工借款”的费用产品
        fee_product = self.env['product.product'].search([('name', '=', '员工借款'),
                                                           ('can_be_expensed', '=', True),
                                                           ('type', '=', 'service')])
        if not fee_product:
            fee_product = self.env['product.template'].create({'name':'员工借款',
                                                               'can_be_expensed': True,
                                                               'type':'service'})
        return fee_product

    def _from_borrowfee_to_expensline(self):
        # 根据借款单的(borrow.fee)信息，创建一张费用明细单(expense.line)
        vals = {'name': self._get_borrow_fee_product().id,
                'price': self.amount,
                'partner_id': self.partner_id.id,
                'borrow_fee_id': self.id,
                'employee_id_2': self.request_user.employee_ids[0].id}
        expense = self.env['expense.line'].create(vals)
        return expense

    #@api.multi
    def boss_approve(self):
        if self.state == 'boss_approve':
            self.state = 'done'


class RequestPaymentType(models.Model):
    # 采购请款单的付款方式
    _name = 'request.payment.type'
    name = fields.Char('名称')
    tax = fields.Boolean('含税的付款方式')



class ReturnFee(models.Model):
    _name = 'return.fee'
    _inherit = ['mail.thread']

    name = fields.Char(copy=False)
    borrow_id = fields.Many2one('borrow.fee', string="借款单据")
    request_user = fields.Many2one('res.users', string="还款员工")
    amount = fields.Monetary(string='还款额', required=True, currency_field='currency_id')
    currency_id = fields.Many2one('res.currency', string='Currency', required=True,
        related="borrow_id.currency_id")
    payment_date = fields.Date('借款日期', default=datetime.now().date())
    discription = fields.Char('备注')
    state = fields.Selection([
        ('boss_approve', '出纳收款'),
        ('done','完成'),
        ('cancelled', '取消')],
        default='boss_approve', copy=False, string="状态", track_visibility="onchange")

    @api.multi
    def cancel(self):
        self.state = 'cancelled'

    #@api.multi
    def financial_approve(self):
        if self.state == 'financial_approve':
            self.state = 'payment_approve'

    #@api.multi
    def payment_approve(self):
        if self.state == 'payment_approve':
            self.state = 'boss_approve'

    @api.multi
    def boss_approve(self):
        self.state = 'done'
        self.update_borrow_fee_state()

    def update_borrow_fee_state(self):
        # 根据还款总额，更新借款单的状态
        borrow_id = self.borrow_id
        if borrow_id.return_fee_total > 0 and borrow_id.return_fee_total >= borrow_id.amount:
            borrow_id.state = 'clear'


class Hr(models.Model):
    _inherit = 'hr.employee'

    private_bank_account = fields.Char('银行账号')
    private_open_bank = fields.Char('开户行')